package org.firecloud.h5fun.controller.service;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.CommonConfig;
import org.firecloud.h5fun.model.CommonFunction;
import org.json.JSONObject;
/**
 * 获取图灵机器人返回信息通过Ajax方法调用URL：ajax_tuling<br>
 * 必须登陆：false<br>
 * 必须管理：false<br>
 * 参数：<br>
 * info，必须，发送的信息<br>
 * 注：无<br>
 * @author fc
 */
public class AjaxTuling extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONObject json = null;
		try {
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/json");
			CommonConfig config = (CommonConfig) req.getServletContext().getAttribute("commonConfig");
			String strInfo = req.getParameter("info");
			if (strInfo != null) {
				if (strInfo.indexOf("随机数") != -1) {
					json = new JSONObject();
					json.put("code", 100000);
					json.put("text", ""+new Random().nextInt(100));
				} else {
					String strJson = CommonFunction.http_read_get(
							String.format("http://www.tuling123.com/openapi/api?key=%s&info=%s&userid=%X",
									config.getTulingApikey(), strInfo, req.getSession().hashCode()));
					json = new JSONObject(strJson);
				}
			} else {
				json = new JSONObject();
				json.put("code", 40008);
				json.put("text", "服务器错误");
			}
		} catch (Exception e) {
			json = new JSONObject();
			json.put("code", 40000);
			json.put("text", "未知错误");
			Logger.getRootLogger().error(e);
		}
		resp.getWriter().print(json);
	}
}
